package com.yvon.service.demo.mybatis.executor;

import com.yvon.service.demo.mybatis.executor.statement.StatementHandler;
import com.yvon.service.demo.mybatis.mapping.BoundSql;
import com.yvon.service.demo.mybatis.mapping.MappedStatement;
import com.yvon.service.demo.mybatis.session.Configuration;
import com.yvon.service.demo.mybatis.session.ResultHandler;
import com.yvon.service.demo.mybatis.transaction.Transaction;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * @author Yvon
 * @since 2023-04-14
 */
public class SimpleExecutor extends BaseExecutor {

    public SimpleExecutor(Configuration configuration, Transaction transaction) {
        super(configuration, transaction);
    }

    /**
     * 方法中包装数据源的获取、语句处理器的创建，以及对 Statement 的实例化和相关参数设置。最后执行 SQL 的处理和结果的返回操作
     *
     * @param ms            ms
     * @param parameter     参数
     * @param resultHandler 结果处理程序
     * @param boundSql      绑定sql
     * @return {@link List}<{@link E}>
     */
    @Override
    protected <E> List<E> doQuery(MappedStatement ms, Object parameter, ResultHandler resultHandler, BoundSql boundSql) {
        try {
            Configuration configuration = ms.getConfiguration();
            StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, resultHandler, boundSql);
            Connection connection = transaction.getConnection();
            Statement stmt = handler.prepare(connection);
            handler.parameterize(stmt);
            return handler.query(stmt, resultHandler);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
